
local table = table

local trigger = class('trigger')

function trigger:ctor(event, callback)
	self.type = 'trigger' 				--结构
	self.enable_flag = true				--是否允许
	self.event = event					--引用lua trigger的事件
    self.callback = callback            --回调
	self.removed = false
end

--禁用触发器
function trigger:disable()
	self.enable_flag = false
end

function trigger:enable()
	self.enable_flag = true
end

function trigger:is_enable()
	return self.enable_flag
end

--运行触发器
function trigger:__call(...)
	if self.removed then
		return
	end
	if self.enable_flag then
		return self:callback(...)
	end
end

--摧毁触发器(移除全部事件)
function trigger:remove()
	if not self.event then
		return
	end	
	local event = self.event
	self.event = nil
	self.removed = true
	ac.wait(0, function()
		for i, trg in ipairs(event) do
			if trg == self then
				table.remove(event, i)
				break
			end
		end
	end)
end

--创建触发器
function ac.trigger(event, callback)
    local trg = trigger.new(event, callback)
	table.insert(event, trg)
	return trg
end

return trigger
